import {wss} from '../model/endpoints';


class SocketClient{
    constructor(){
        this.socketOpen = false;
        this.socketMsgQueue = [];
        this.listeners = [];
        this.userId = wx.getStorageSync('open_id');
        this.timer = null;
        this.defaultMsg = {
            from : this.userId,
            from_nick: '小黑黑',
            to: '',
            content: ''
        };
        this.serverUrl = wss + this.userId;
    }
    init(){
        const _this = this;
        wx.connectSocket({
            url: this.serverUrl
        });
        wx.showLoading({
            title: '网络连接中...',
        });
        /**
         * socket 连接成功
         */
        wx.onSocketOpen(function(res) {
            _this.socketOpen = true;
            console.log('【socket】socket 连接成功');
            for (let i = 0; i < _this.socketMsgQueue.length; i++){
                _this.sendSocketMessage(_this.socketMsgQueue[i]);
            }
            _this.socketMsgQueue = [];
            /**
             * 心跳报
             */
            // _this.timer =  setInterval(()=>{
            //     _this.sendSocketMessage('ping');
            // },3000);
            wx.hideLoading();
        });
        wx.onSocketMessage(message => {
            console.log('【socket】接收到消息',message);
            _this.listeners.forEach(listener => {
                listener(message);
            });
        });

        wx.onSocketError((result) => {
            console.log('【socket】socket error',result);
            clearInterval(this.timer);
            this.timer = null;
        });

        wx.onSocketClose((result) => {
            console.log('【socket】socket closed',result);
            clearInterval(this.timer);
            this.timer = null;
        });
        
    }
    /**
    * 发送消息
    * @param {*} msg 
    */
    sendSocketMessage(msg){
        if(msg == 'ping'){
            return wx.sendSocketMessage({ data:msg });
        }
        msg = Object.assign({},this.defaultMsg, msg);
        msg = JSON.stringify(msg);
        if (this.socketOpen) {
            wx.sendSocketMessage({
                data:msg
            });
        } else {
            this.socketMsgQueue.push(msg);
        }
    }
    /**
     * 注册消息监听
     * @param {*} fn 
     */
    onSocketMessage(fn){
        this.listeners.push(fn);
    }
    /**
     * 关闭socket
     */
    close(){
        wx.closeSocket();
    }

}

export default SocketClient;